package com.xingfly.web.api;

import com.xingfly.authentication.annotation.Authorization;
import com.xingfly.authentication.annotation.Me;
import com.xingfly.constant.ApiConstant;
import com.xingfly.constant.ErrorConstant;
import com.xingfly.constant.HttpStatus;
import com.xingfly.constant.Type;
import com.xingfly.error.TipException;
import com.xingfly.model.Event;
import com.xingfly.model.Image;
import com.xingfly.model.Post;
import com.xingfly.model.User;
import com.xingfly.model.vo.ImageVO;
import com.xingfly.model.vo.PostVO;
import com.xingfly.service.*;
import com.xingfly.web.model.ResponseModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by SuperS on 22/05/2017.
 *
 * @author SuperS
 */
@RestController
@RequestMapping("/api/posts")
@Api(value = "posts", description = "posts相关操作")
public class PostController {
    @Autowired
    private PostService postService;
    @Autowired
    private EventService eventService;
    @Autowired
    private FeedService feedService;
    @Autowired
    private NotificationService notificationService;
    @Autowired
    private ImageService imageService;

    @ApiOperation(value = "创建Post", notes = "验证后创建Post(创建Post并丢给队列进行Notification和Feed流处理)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "postVO", value = "postVO", dataType = "PostVO", required = true),
            @ApiImplicitParam(name = "authorization", value = ApiConstant.AUTHORIZATION, paramType = "header", dataType = "String", required = true)
    })
    //需要用户登录
    @Authorization
    @PostMapping
    public ResponseModel createPost(@ApiIgnore @Me User me, @RequestBody PostVO postVO) throws TipException {
        //用户发表的动态内容为空
        if (StringUtils.isEmpty(postVO.getContent())) {
            throw new TipException(ErrorConstant.ERROR_MSG_ARGUMENT_NOT_NULL, ErrorConstant.ERROR_CODE_ARGUMENT_NOT_NULL);
        }
        postVO.setCreateTime(new Date());
        //发表动态
        Post saved = postService.send(me, postVO);

        List<ImageVO> imageVOS = new ArrayList<>();
        //如果post带有图片
        if (postVO.getImageVOS() != null) {
            for (ImageVO imageVO : postVO.getImageVOS()) {
                //根据图片id遍历图片
                Image image = imageService.findById(imageVO.getId());
                //添加到图片VO列表中
                imageVOS.add(ImageVO.toVO(image));
            }
        }
        return ResponseModel.builder().message(HttpStatus.STATUS_INFO_CREATED).code(HttpStatus.STATUS_CODE_CREATED).data(PostVO.toVO(saved, imageVOS)).build();
    }

    @ApiOperation(value = "删除Post", notes = "验证后通过ID删除Post")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", dataType = "Long", paramType = "path", required = true),
            @ApiImplicitParam(name = "authorization", value = ApiConstant.AUTHORIZATION, paramType = "header", dataType = "String", required = true)
    })
    @DeleteMapping("{id}")
    //需要用户登录
    @Authorization
    @Transactional
    public ResponseModel deletePost(@PathVariable("id") Long id, @ApiIgnore @Me User me) throws TipException {
        Post post = postService.findById(id);
        if (post == null) {
            throw new TipException(ErrorConstant.ERROR_MSG_POST_NOT_FOUND, ErrorConstant.ERROR_CODE_POST_NOT_FOUND);
        }
        //判断当前post作者是不是登录用户
        if (!post.getAuthor().getId().equals(me.getId())) {
            throw new TipException(ErrorConstant.ERROR_MSG_USER_NOT_MATCH, ErrorConstant.ERROR_CODE_USER_NOT_MATCH);
        }
        //获取事件
        Event event = eventService.findByObjIdAndType(id, Type.EVENT_POST);
        //删除feed
        feedService.deleteAllByEventId(event.getId());
        //删除notifications
        notificationService.deleteAllByEventId(event.getId());
        //删除相关的图片连接
        imageService.deleteAllByEvent(event);
        //删除event
        eventService.deleteAllByEventObjectIdAndType(id, Type.EVENT_POST);
        //删除post
        postService.deleteById(id);
        return ResponseModel.builder().message(HttpStatus.STATUS_INFO_ACCEPTED).code(HttpStatus.STATUS_CODE_ACCEPTED).build();
    }
}
